package com.example.redis.util;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Resource
    private RedisTemplate<String, Object> mRedisTemplate;

    public void set(String key, Object value, long time) {
        mRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }

    public void set(String key, Object value) {
        mRedisTemplate.opsForValue().set(key, value);
    }

    public Object get(String key) {
        return mRedisTemplate.opsForValue().get(key);
    }

    public Object get(String key, Object o) {
        return mRedisTemplate.opsForHash().get(key, o);
    }

    public Boolean delete(String key) {
        return mRedisTemplate.delete(key);
    }

    public Long delete(List<String> keys) {
        return mRedisTemplate.delete(keys);
    }

    public Boolean expire(String key, long time) {
        return mRedisTemplate.expire(key, time, TimeUnit.SECONDS);
    }

    public Long getExpire(String key) {
        return mRedisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    public Boolean hasKey(String key) {
        return mRedisTemplate.hasKey(key);
    }

    public Long incr(String key, long delta) {
        return mRedisTemplate.opsForValue().increment(key, delta);
    }

    public Long decr(String key, long delta) {
        return mRedisTemplate.opsForValue().decrement(key, delta);
    }

    public Map<Object, Object> getMap(String key){
        return mRedisTemplate.opsForHash().entries(key);
    }

    public void setMap(String key, Map<String, Object> value){
        mRedisTemplate.opsForHash().putAll(key, value);
    }

    public void setMap(String key, Map<String, Object> value, long time){
        mRedisTemplate.opsForHash().putAll(key, value);
        if (time > 0){
            expire(key, time);
        }
    }

    public <T> T execute(RedisScript<T> script, List<String> keys, Object... args) {
        return mRedisTemplate.execute(script, keys, args);
    }

}
